package com.travelsky.server.chat_socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import com.travelsky.server.jdbc.Base64Util;
import com.travelsky.server.jdbc.Dao;
import com.travelsky.server.vo.group.ProjectGroup;

/**
 * 代码提交工具服务器类
 ******************************************
 * @author HuangFeng  [2017年7月4日 下午5:39:56]
 * @version 1.0
 ******************************************
 */
public class Server extends Thread{
	
	private ServerSocket serverSocket;
	private int Port = 5000;		//设置服务器端口
	private boolean flag_exit = false;
	public Map<String, ServerThread> serverThreadList; 
	public String version = "V1.5.2";
	public String updateMessage = "此次更新内容：1.增加5分钟不提代码提示的功能,避免长时占用";
	public List<ProjectGroup> projectGroups;
	public Dao dao;
	private String mail_username;
	private String mail_password;
	private String mail_from;
	private String mail_host;
	
	/**
	 * 构造函数
	 ******************************************
	 * @author HuangFeng [2017年7月4日 下午5:40:44]
	 * @version 1.0
	 ******************************************
	 */
	public Server(){
		try {
			serverSocket = new ServerSocket(Port);  //创建指定端口号的服务器套接字
		} catch (IOException e) {
			System.exit(0);
		}
		serverThreadList = Collections.synchronizedMap(new HashMap<String, ServerThread>());
		dao = new Dao();
		// 加载配置文件
		Properties prop = new Properties();
		try {
			prop.load(this.getClass().getClassLoader().getResourceAsStream("server.properties"));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		this.mail_username = Base64Util.base64decode(prop.getProperty("mail_username"));
		this.mail_password = Base64Util.base64decode(prop.getProperty("mail_password"));
		this.mail_from = Base64Util.base64decode(prop.getProperty("mail_from"));
		this.mail_host = Base64Util.base64decode(prop.getProperty("mail_host"));
	}
	
	public static void main(String[] args) {
		Server server = new Server();
		//启动服务器
		server.startServer(); 
	}
	
	/**
	 * 启动服务器
	 ******************************************
	 * @author HuangFeng [2017年7月4日 下午5:40:58]
	 * @version 1.0
	 ******************************************
	 */
	public void startServer() {
		this.flag_exit = true;
		this.run();
	}
	
	@Override
	public void run() {
		Socket socket; // 创建套接字
		while (flag_exit) {
			try {
				if (serverSocket.isClosed()) { // 如果服务器套接字关闭
					flag_exit = false; // 将标志设置为false
				} else {
					try {
						socket = serverSocket.accept(); // 侦听到服务器套接字的连接，连接之前，一直阻塞
					} catch (SocketException e) {
						socket = null;
						flag_exit = false;
					}
					if (socket != null) { // 连接成功
						socket.setSoTimeout(8000);//设置超时时间8秒
						
						List<ProjectGroup> list = dao.queryAllProjectGroup();
						if(list != null && list.size() > 0){
							projectGroups = list;
						}
						ClientThread clientThread = new ClientThread(socket,this);
						clientThread.setFlag_exit(true);
						clientThread.start(); // 启动一个客户端线程
						clientThread.dos.writeUTF(this.version+"@updateVersion");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 登录方法
	 ******************************************
	 * @author HuangFeng [2017年10月29日 上午1:11:03]
	 * @version 1.0
	 ******************************************
	 * @param groupName 项目组名
	 * @param username 用户名
	 * @param clientThread 客户端线程
	 */
	public void login(String groupName, String username, ClientThread clientThread) {
		ServerThread serverThread;
		synchronized(serverThreadList){
			if(!serverThreadList.containsKey(groupName)){
				serverThread = new ServerThread(this,groupName);
				serverThreadList.put(groupName, serverThread);
			}
			serverThread = serverThreadList.get(groupName);
		}
		clientThread.setServerThread(serverThread);
		serverThread.login(groupName,username,clientThread);
	}
	
	/**
	 * 发送错误信息邮件
	 ******************************************
	 * @author HuangFeng [2017年8月29日 下午12:01:23]
	 * @version 1.0
	 ******************************************
	 * @param content
	 */
	public void sendEmail(String content){
		Properties properties = new Properties();
		properties.setProperty("mail.host", mail_host);
		properties.setProperty("mail.smtp.auth", "true");
		Authenticator auth = new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication(){
				return new PasswordAuthentication(mail_username, mail_password);
			}
		};
		Session session = Session.getInstance(properties, auth);
		MimeMessage message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(mail_from));
			message.setRecipients(RecipientType.TO, "huangf@travelsky.com");
			message.setSubject("代码提交工具出错了");
			message.setContent(content,"text/html;charset=utf-8");
			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
	}
	
}
